package com.example.coroutinelearn.down_load_demo

import java.io.InputStream
import java.io.OutputStream

/**
 * @author huangzehui
 * @date 7/6/2024 下午11:41 周五
 * @description
 */


/**
 * 将 InputStream 写入 out 中
 * @param out 输出流
 * @param bufferSize 缓冲区大小，默认 8 M
 * @param progress 写入进度的回调
 */
inline fun InputStream.copyTo(
    out: OutputStream,
    bufferSize: Int = DEFAULT_BUFFER_SIZE,
    progress: (byteCopied: Long) -> Unit
): Long {
    var bytesCopied: Long = 0
    val buffer = ByteArray(bufferSize)
    var bytes = read(buffer)
    while (bytes > 0) {
        out.write(buffer, 0, bytes)
        bytesCopied += bytes
        bytes = read(buffer)

        progress(bytesCopied)
    }
    return bytesCopied
}